package com.springbootblog.filter;

import com.springbootblog.service.fontend.LoginService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;


@WebFilter(urlPatterns = "/java/*", filterName = "FontendsFilter")
public class FontendsFilter implements Filter
{
    private LoginService loginService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {
        //过滤器注入service，原因：过滤器执行的时候，service还没有被实例化注入
        ServletContext sc = filterConfig.getServletContext();
        WebApplicationContext cxt = WebApplicationContextUtils.getWebApplicationContext(sc);
        if(cxt != null)
        {
            if (loginService == null)
            {
                // 注入service类
                loginService = cxt.getBean(LoginService.class);
            }
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
    {
        // System.out.println("FontendsFilter.doFilter");
        // servletRequest.setCharacterEncoding("utf-8");
        // 强转
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        // 获取header参数，例如获取名为"X-Custom-Header"的header
        String headerValue = request.getHeader("token");
        System.out.println("filter:"+headerValue);

        // ================================================================================
        // 单点登录逻辑
//        try
//        {
            Map<String, Object> result = loginService.checkSingleLogin(request);
            if((int)result.get("code") < 0)
            {
                // 设置头部返回信息
                response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
                response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
                response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
                response.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token,token");//这里“Access-Token”是我要传到后台的内容key
                response.addHeader("Access-Control-Expose-Headers", "*");
                response.setHeader("Access-Control-Allow-Credentials", "true");
                response.setHeader("Cache-Control", "no-cache");
                // 设置前端状态码和内容类型 设置响应状态码为 200。
                response.setStatus(HttpServletResponse.SC_OK);
                // 设置响应内容类型
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");

                // 直接写入响应体
                String jsonResponse = "{\"code\": \"-150\",\"msg\": \"您的账号在另一地点登录！\"}";
                //System.out.println("filter-map:"+jsonResponse);
                response.getWriter().write(jsonResponse);
                return;
            }
        /*}
        catch (Exception e)
        {
            System.out.println("Filter 出错了");
            throw new RuntimeException(e);
        }//*/
        // 继续执行下边的代码
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {}

}